// 这是引入不同的env文件
// require('dotenv').config();  加载根目录下面的.env文件
require('dotenv').config();
const express = require('express');
const user = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
//用于临时令牌
const crypto = require('crypto');

//路径包
const path = require("path");
//获取启动项目录
const rootDir = process.cwd();

//引入方法
//引入授权中间件
const authenticateToken = require(path.join(rootDir, "/middlewares/authMiddleware"));
//引入移动检测中间件
const mobiledetect = require(path.join(rootDir, './middlewares/mobiledetect'));

//引入数据表
//lokijs数据库用户表
let userloki = require(path.join(rootDir, "lokisheets/userDB"));

// 生成一次性临时认证码
const tempTokens = new Map();


//区分手机电脑页面中间件
user.use(mobiledetect);

//根路由-用户信息界面
user.get("/", (req, res) => {
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/user/info.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/user/info.html");
    }
});

//登录界面
user.use("/loginshow", (req, res) => {
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/user/loginshow.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/user/loginshow.html");
    }
});

//注册界面
user.use("/registershow", (req, res) => {
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/user/registershow.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/user/registershow.html");
    }
});




// 注册接口
user.post('/register', async (req, res) => {
    try {
        let reqData = { ...req.body, ...req.query };
        let user = await userloki.find({ Useraccount: reqData.Useraccount });
        if (user.data.length !== 0) {

            return res.json({ message: { data: '用户名已存在', success: false } });
        }

        //嘻哈密码，非明文保存
        const hashedPassword = await bcrypt.hash(reqData.Userpassword, 10);
        let saveData = {
            Useraccount: reqData.Useraccount,
            Userpassword: hashedPassword
        }

        let result = await userloki.create(saveData);
        if (result.success) {
            let user = await userloki.find({ Useraccount: reqData.Useraccount });
            if (user.success) {
                //创建令牌
                const token = jwt.sign(
                    {
                        userid: user.data[0].User_id
                    },
                    process.env.JWT_SECRET,
                    {
                        expiresIn: '1h'
                    }
                );
                res.json({ message: { data: token, success: true } });
            } else {
                res.json({ message: { data: "查询不到用户名", success: false } });
            }
        } else {
            res.json({ message: { result, success: false } });
        }
    } catch (err) {
        res.json({ error: '程序错误', err });
    }
});

// 登录接口
user.post('/login', async (req, res) => {
    try {
        let reqData = { ...req.body, ...req.query };
        let user = await userloki.find({ Useraccount: reqData.Useraccount });

        if (!user.success) {
            return res.json({ message: { data: '用户不存在', success: false } });
        }
        //执行查找到的数据将密码进行解密
        const isMatch = await bcrypt.compare(reqData.Userpassword, user.data[0].Userpassword);

        if (!isMatch) return res.json({ message: { data: '密码错误', success: false } });
        //创建令牌
        const token = jwt.sign(
            {
                userid: user.data[0].User_id
            },
            process.env.JWT_SECRET,
            {
                expiresIn: '1h'
            }
        );
        res.json({ message: { data: token, success: true } });
    } catch (err) {
        res.json({ message: { data: '登录失败', success: false, error: err.message } });
    }
});


module.exports = user;